package top.cdmrx.demo.edu.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;
import top.cdmrx.demo.edu.entity.Subject;
import top.cdmrx.demo.edu.entity.excel.SubjectData;
import top.cdmrx.demo.edu.entity.subject.OneSubject;
import top.cdmrx.demo.edu.entity.subject.TwoSubject;
import top.cdmrx.demo.edu.listener.SubjectEventListener;
import top.cdmrx.demo.edu.mapper.SubjectMapper;
import top.cdmrx.demo.edu.service.SubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2021-09-14
 */
@Service
public class SubjectServiceImpl extends ServiceImpl<SubjectMapper, Subject> implements SubjectService {

    @Autowired
    private SubjectEventListener subjectEventListener;

    //添加课程分类
    @Override
    public void saveSubject(MultipartFile file) {


        try {
            InputStream inputStream = file.getInputStream();

            EasyExcel.read(inputStream, SubjectData.class,subjectEventListener).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<OneSubject> getAllOneAndTwoSubject() {
        //查询一级分类
        QueryWrapper<Subject> subjectQueryWrapper = new QueryWrapper<>();
        subjectQueryWrapper.eq("parent_id",0);

        List<Subject> list1 = this.list(subjectQueryWrapper);

        //查询二级分类

        QueryWrapper<Subject> subjectQueryWrapper1 = new QueryWrapper<>();
        subjectQueryWrapper1.ne("parent_id",0);

        List<Subject> list2 = this.list(subjectQueryWrapper1);
        //创建总的集合封装数据

        List<OneSubject> finalList=new ArrayList<>();
        //封装一级分类

        for (int i = 0; i <list1.size(); i++) {
            Subject subject = list1.get(i);
            OneSubject oneSubject = new OneSubject();
            BeanUtils.copyProperties(subject,oneSubject);


            //封装二级分类
            List<TwoSubject> twoSubjectList=new ArrayList<>();
            for (int j = 0; j <list2.size(); j++) {

                Subject subject1 = list2.get(j);

                if (subject1.getParentId().equals(oneSubject.getId())){
                    TwoSubject twoSubject=new TwoSubject();
                    BeanUtils.copyProperties(subject1,twoSubject);
                    twoSubjectList.add(twoSubject);

                }

            }

            oneSubject.setChildren(twoSubjectList);

            finalList.add(oneSubject);

        }
        return finalList;
    }
}
